app.controller('ReportCtrl', [
    '$scope', 'alertService', 'reportService', 'APP_CONFIG', '$rootScope', '$timeout',
    function ($scope, alertService, reportService, APP_CONFIG, $rootScope, $timeout) {
        reportService.getAsync()
            .then(function (result) {
                $scope.reportList = result;
            }, alertService.error);

        $scope.selected = {};

        $scope.start = new Date();

        $scope.end = new Date();

        $scope.select = function (r) {
            $scope.selected = r;
        };

        $scope.isActive = function (reportId) {
            return $scope.selected.Id == reportId;
        };

        $scope.openCalendar = function ($event, target) {
            $event.preventDefault();
            $event.stopPropagation();
            if (target === 'start') {
                $scope.isStartOpen = true;
            }
            else if (target === 'end') {
                $scope.isEndOpen = true;
            }
        };

        $scope.submit = function () {
            if (!$scope.selected) {
                alertService.add('请选择要统计的报表');
                return;
            }

            reportService.downAsync(+$scope.selected.Id, moment($scope.start).format('YYYY-MM-DD'), moment($scope.end).format('YYYY-MM-DD'))
                .then(function (url) {
                    $scope.downloadUrl =APP_CONFIG.apiHost+url;
                    $rootScope.loading = true;
                    $timeout(function () {
                        $rootScope.loading = false;
                    }, 1e3);
                },alertService.error);
        };
    }
]);

app.factory('reportService', [
    '$http', '$q',
    function ($http, $q) {
        var self = {};

        self.getAsync = function () {
            var defer = $q.defer();
            $http({
                url: '/api/report'
            }).success(function (result) {
                if (result.Code >= 0) defer.resolve(result.Data);
                else defer.reject(result.Message);
            }).error(function (x) {
                console.error(x);
                defer.reject('查询报表列表失败，请稍后再试');
            })
            return defer.promise;
        };

        self.downAsync = function (reportId, start, end) {
            var defer = $q.defer();
            $http({
                url: '/api/report',
                method: 'POST',
                params: {
                    reportId: reportId,
                    start: start,
                    end: end
                }
            }).success(function (result) {
                if (result.Code >= 0) defer.resolve(result.Message);
                else defer.reject(result.Message);
            }).error(function (x) {
                console.error(x);
                defer.reject('下载报表失败，请稍后再试');
            })
            return defer.promise;
        };

        return self;
    }
]);